<template>
  <div class="common-layout">
    <el-row :gutter="20">
      <el-col :span="4">
        <div class="grid-content ep-bg-purple1">
          <div class="title1">
            商品类型列表
          </div>
          <el-tree style="max-width: 600px" :load="loadNode" lazy :props="props" @node-click="handleNodeClick"
            accordion />
        </div>
      </el-col>
      <el-col :span="20">
        <div class="grid-content ep-bg-purple2">
          <div class="title2">
            商品{{ title }}
          </div>
          <el-form ref="ruleFormRef" style="max-width: 1000px" :model="goodsInfo" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="所属分类" prop="category">
              <span>{{ goodsInfo.category }}</span>
            </el-form-item>
            <el-form-item label="商品名称" prop="title">
              <el-input v-model="goodsInfo.title" />
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="goodsInfo.price" />
            </el-form-item>
            <el-form-item label="商品数量" prop="num">
              <el-input v-model="goodsInfo.num" />
            </el-form-item>
            <el-form-item label="商品卖点" prop="sellPoint">
              <el-input v-model="goodsInfo.sellPoint" />
            </el-form-item>
            <el-form-item label="商品图片" prop="image">
              <Uploadimg @getimg="getimg" :imgs="goodsInfo.image" ref="deleteimg"></Uploadimg>
            </el-form-item>
            <el-form-item label="商品描述" prop="descs">
              <WangEditor ref="desc" @getdesc="getdesc"></WangEditor>
            </el-form-item>
            <el-form-item label="首页轮播推荐" prop="isShow">
              <el-switch v-model="goodsInfo.isShow"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
            </el-form-item>
            <el-form-item label="是否推荐商品" prop="isShow">
              <el-switch v-model="goodsInfo.isShow"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
            </el-form-item>
            <el-form-item label="是否上架商品" prop="isShow">
              <el-switch v-model="goodsInfo.isShow"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                Create
              </el-button>
              <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
              <el-button @click="tolist">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, computed, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import Uploadimg from './Uploadimg.vue';
import WangEditor from './WangEditor.vue';
import { ElMessage } from 'element-plus';
import { userowDataStore } from '@/store/modules/product';

const rowDataStore = userowDataStore();
const router = useRouter();
// 全局导入
const cxt = getCurrentInstance();
const API = cxt.appContext.config.globalProperties.$API;
onMounted(() => {
  if (title.value == '编辑' || title.value == '详情') {
    editolddata()
  }
})
const props = {
  label: 'name',
  children: 'zones',
  isLeaf: 'leaf',
};

const loadNode = (node, resolve) => {
  if (node.level === 0) {
    API.selectItemCategoryByParentId().then((res) => {
      if (res.status === 200) {
        return resolve([...res.result]);
      }
    }).catch((error) => console.error(error));
  } else if (node.level === 1) {
    API.selectItemCategoryByParentId({ type: node.data.cid }).then((res) => {
      if (res.status === 200) {
        return resolve([...res.result]);
      }
    }).catch((error) => console.error(error));
  } else {
    return resolve([]);
  }
};

const handleNodeClick = (data) => {
  goodsInfo.category = data.name;
};

const formSize = ref('default');
const ruleFormRef = ref();
const goodsInfo = reactive({
  id: '',
  title: '',
  num: '',
  price: '',
  sellPoint: '',
  image: '',
  descs: '',
  category: '',
  cid: '',
  isShow: true,
});

const rules = reactive({
  title: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
  ],
  num: [
    { required: true, message: '请输入商品数量', trigger: 'blur' },
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
  ],
  category: [
    { required: true, message: '请选择商品类目', trigger: 'blur' },
  ],
});

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      goodsInfo.image = imgsurl.value;
      if (title.value === '添加') {
        goodsInfo.id = '';
        submitinsertTbItem(goodsInfo);
      } else {
        updateTbItem(goodsInfo);
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 重置表单函数
const resetForm = (formEl) => {
  if (!formEl) return
  if (title.value == '添加') {
    formEl.resetFields()
    deleteimg.value.clear()
    desc.value.editorRef.clear()
  } else {
    editolddata()
  }
}

const imgsurl = ref('');
const getimg = (val) => {
  imgsurl.value = JSON.stringify(val);
};

const submitinsertTbItem = async (data) => {
  const res = await API.insertTbItem(data);
  if (res.status === 200) {
    ElMessage({
      message: '添加商品成功',
      type: 'success',
    });
    router.push('/product/list');
  }
};

const updateTbItem = async (data) => {
  const res = await API.updateTbItem(data);
  if (res.status === 200) {
    ElMessage({
      message: '修改商品成功',
      type: 'success',
    });
    router.push('/product/list');
  }
};

const desc = ref(null);
const deleteimg = ref(null)
const getdesc = (val) => {
  goodsInfo.descs = val;
};

const tolist = () => {
  router.push('/product/list');
};

// 读取 pinia 里存放的要编辑的数据
const rowdata = computed(() => rowDataStore.rowData);
const title = computed(() => rowDataStore.title);

onMounted(() => {
  if (title.value === '编辑' || title.value === '详情') {
    editolddata();
  }
});

const editolddata = () => {
  for (const key in goodsInfo) {
    if (goodsInfo.hasOwnProperty(key) && rowdata.value.hasOwnProperty(key)) {
      // 如果 row 中存在相同的属性，则将其值赋给 goodsInfo 中对应的属性
      goodsInfo[key] = rowdata.value[key];
    }
  }
  goodsInfo.image=''
  nextTick(() => {
    desc.value.valueHtml = goodsInfo.descs;
    goodsInfo.image=rowdata.value.image
  });
};
</script>

<style lang="less" scoped>
.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.ep-bg-purple1 {
  height: 600px;
  background: #fff;

  .title1 {
    background: skyblue;
    padding: 20px;
    color: #fff;
  }

  .el-tree {
    padding: 10px;
  }
}

.ep-bg-purple2 {
  background: #fff;

  .title2 {
    background: #eee;
    padding: 14px;
    color: #333;
    font-weight: bold;
  }

  .demo-ruleForm {
    padding: 30px;
  }
}
</style>